<input type="text" class="name"> 姓名
<input type="text" class="age"> 年龄
<button class="get">点击请求get数据</button>
<button class="post">点击请求post数据</button>
<hr>

<span>您好:</span>
<span id="name"></span>
<span>你的年龄是</span>
<span id="age"></span>

<hr>
<img src="/img/ajax/img_packaging.png" alt="">


<script>
    $.myAjax = function(method = 'GET', url, data = null, callback) {
        const xhr = new XMLHttpRequest()
        let str = Object.keys(data).map(key => `${key}=${data[key]}`).join('&')
        method = method.toUpperCase()
        if (method === 'GET') {
            url += '?' + str
            str = null;
        }
        xhr.open(method, url, true)
        if (method === 'POST') {
            xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded")
        }
        xhr.onreadystatechange = function() {
            if (this.readyState === 4 && this.status == 200) {
                let res = JSON.parse(this.responseText)
                callback(res);
            }
        }
        xhr.send(str)
    }
    $('button').on('click', function() {
        let name = $('.name').val()
        let age = $('.age').val()
        const BASE_URL = 'http://api.hyfarsight.com/example/';
        let url = '';
        let method = 'get'

        if ($(this).hasClass('get')) {
            url = 'demo1'
        } else {
            url = 'demo2'
            method = 'post'
        }
        $.myAjax(method, BASE_URL + url, {
            name: name,
            age: age
        }, function(res) {
            if (res.code === 0) {
                $('#name').html(res.data.name)
                $('#age').html(res.data.age)
            }
        })
    })
</script>